/**
 *
 * @date 2019/12/16 0016
 * @author jiawei
 */
import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import { MessageBox, Message } from "element-ui";

//创建axios对象，配置基础url
const ajax = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000
})

// 让ajax携带cookie
ajax.defaults.withCredentials = true
//拦截请求，进行设置请求头
ajax.interceptors.request.use(
  // 每次请求都自动携带Authorization请求头
  config => {
    config.headers.Authorization = store.state.token
    return config
  },
  error => {
    return Promise.reject(error);
  })

//拦截响应请求
ajax.interceptors.response.use(
  rsp => {
    let head = rsp.headers.authorization
    if (!Vue.prototype.$isEmpty(head)) {
      sessionStorage.setItem("ACCESS_TOKEN", head)
      store.commit('setToken', head)
    }
    return rsp
  },
  // 拦截异常的响应
  err=>{

    switch (err.response.status) {
      case 401:
        MessageBox.alert('登陆已过期，请重新登录')
        break
      case 403:
        Message.warning("抱歉，您无权访问！")
        break
      case 500:
        Message.error("服务器出了点小错误")
        break
      default:
        return Promise.reject(err);
    }
    return Promise.reject(err);
  }
)

export default ajax
